package ui.fragment.minefragment;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Looper;
import android.support.v4.app.Fragment;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.linchaolong.android.imagepicker.ImagePicker;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import Dailog.CommomDialog;
import base.BaseBean;
import base.fragment.BaseNetFragment;
import bean.PersonInfoBean;
import student.andlei.com.student.R;
import ui.fragment.MineFragment;
import ui.fragment.homepagefragment.AllFragment;
import utils.GlideUtils;
import utils.GsonUtils;
import utils.Logger;
import utils.QiniuUploadUtils;
import utils.SPUtils;
import utils.StringUtils;

/**
 * 个人信息
 */
public class PersonInfoFragment extends BaseNetFragment{
    private ImageView img_photo;
    private RelativeLayout rlayout_head_img;
    private TextView tv_school,
                tv_grade_class,
                tv_phonenumber,
                tv_name,
                tv_usernumber,
                tv_part;
    private EditText ed_associated_parents;
    private Button bt_save;
    private ImagePicker imagePicker;
    private String  path;
    private String  oldpath;
    private int school_status;
    public static Fragment getInstance() {
        return new PersonInfoFragment();
    }
    @Override
    public void success(String action, BaseBean baseBean) {
        hideLoadDialog();
        if(action.equals("personal/getInfo")){
            if(baseBean.code == 200){
                PersonInfoBean Bean = (PersonInfoBean) GsonUtils.JSONToObject(GsonUtils.beanToJSONString(baseBean.data), PersonInfoBean.class);
                SPUtils.getInstance(context).put("head_image",Bean.head_image);
                GlideUtils.loadImageViewHeadphotoLoding(context, Bean.head_image, img_photo);
                oldpath = Bean.head_image;
                tv_name.setText("" + Bean.real_name);
                SPUtils.getInstance(context).put("name",Bean.real_name);
                tv_school.setText(Bean.school_name+"    ");
                tv_grade_class.setText(Bean.schedule_name+"    ");
                tv_phonenumber.setText(Bean.mobile);
                ed_associated_parents.setText(Bean.parent_mobile);
                tv_usernumber.setText(Bean.student_id+"");
                //学校审核状态 0没有学校 10待申请 20待审核 30审核失败 100通过
                school_status = Bean.school_status;
                switch (Bean.school_status){
                    case 0:
                        tv_school.setText("申请加入学校");
                        tv_grade_class.setEnabled(false);
                        break;
                    case 10:
                        tv_school.setText("申请加入学校");
                        tv_grade_class.setEnabled(false);
                        break;
                    case 20:
                        tv_school.setText(Bean.school_name);
                        tv_grade_class.setEnabled(false);
                        break;
                    case 30:
                        break;
                    case 100:
                        tv_grade_class.setEnabled(true);
                        break;
                }
                if(StringUtils.isNull(tv_school.getText().toString())){
                    ((MineFragment)getParentFragment()).tv_school.setText("");
                }
            }else {
                toast(baseBean.msg);
            }
        }else if(action.equals("personal/editInfo")){
            if(baseBean.code == 200){
                toast("修改信息成功");
            }else {
                toast(""+baseBean.msg);
            }
        }
    }

    @Override
    public void error(String action, Throwable e) {
        hideLoadDialog();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_personinfo;
    }

    @Override
    protected void findViews() {
        imagePicker = new ImagePicker();
        imagePicker.setCropImage(false);
        img_photo = getView(R.id.img_photo);
        rlayout_head_img = getView(R.id.rlayout_head_img);
        tv_school = getView(R.id.tv_school);
        tv_grade_class = getView(R.id.tv_grade_class);
        tv_phonenumber = getView(R.id.tv_phonenumber);
        ed_associated_parents = getView(R.id.ed_associated_parents);
        tv_name = getView(R.id.tv_name);
        tv_usernumber = getView(R.id.tv_usernumber);
        tv_part = getView(R.id.tv_part);
        bt_save = getView(R.id.bt_save);
    }

    @Override
    protected void formatViews() {
        img_photo.setOnClickListener(this);
        rlayout_head_img.setOnClickListener(this);
        tv_school.setOnClickListener(this);
        tv_grade_class.setOnClickListener(this);
        bt_save.setOnClickListener(this);

    }
    private void loadData(){
        post("personal/getInfo",BaseBean.class,false);
    }
    @Override
    protected void formatData() {
        loadData();
    }

    @Override
    protected void getBundle() {

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            //保存
            case R.id.bt_save:
                if(StringUtils.isNull(path)&&StringUtils.isNull(ed_associated_parents.getText().toString().trim())){toast("修改信息成功");return;}
                if(StringUtils.isNull(path)){
                    Map<String,String> map = new HashMap<>();
                    map.put("head_image",oldpath+"");
                    map.put("parent_mobile",""+ed_associated_parents.getText().toString().trim());
                    post("personal/editInfo",map,BaseBean.class,true);
                }else {
                    showLoadDialog();
                   // Uri uri = Uri.parse(path);
                    //SPUtils.getImageAbsolutePath(getActivity(),uri)
                    QiniuUploadUtils.getInstance().uploadFile(path, new QiniuUploadUtils.UploadListener() {
                        @Override
                        public void onUploadSuccess(String key) {
                            hideLoadDialog();
                            String yuming = SPUtils.getInstance(getActivity()).getString("domain");
                            String image = yuming+key;
                            Logger.i("onUploadSuccess",yuming);
                            Logger.i("onUploadSuccess",key);
                            Map<String,String> map = new HashMap<>();
                            map.put("head_image",""+image);
                            map.put("parent_mobile",""+ed_associated_parents.getText().toString().trim());
                            post("personal/editInfo",map,BaseBean.class,false);
                        }

                        @Override
                        public void onUploadFail(Error error) {
                            hideLoadDialog();
                            Looper.prepare();
                            toast("修改信息失败");
                            Looper.loop();
                        }
                    },SPUtils.getInstance(getActivity()).getString("uptoken"));
                }

                break;
            //选择学校
            case R.id.tv_school:
                if(school_status == 20){
                    new CommomDialog(getActivity(), R.style.dialog, "学校正在审核中，请耐心等待!", new CommomDialog.OnCloseListener() {
                        @Override
                        public void onClick(Dialog dialog, boolean confirm) {
                            if (confirm) {
                                dialog.dismiss();
                            }
                        }
                    }).setTitle("提示").hideNegativeButton().settPositiveButtonColor(R.color.homepage_titlefont).show();
                }else {
                    ((MineFragment)(this.getParentFragment())).Updatetype ="学校";
                    ((MineFragment)(this.getParentFragment())).GojumpSelectSchoolFragment();
                }
                break;
            //选择班级
            case R.id.tv_grade_class:
                ((MineFragment)(this.getParentFragment())).Updatetype ="班级";
                ((MineFragment)(this.getParentFragment())).GojumpSelectSchoolFragment();
                break;
             //修改头像
            case R.id.img_photo:
                openPhoto();
                break;
            //修改头像
            case R.id.rlayout_head_img:
                openPhoto();
                break;
        }
    }
    private List<LocalMedia> selectList = new ArrayList<>();
    private void openPhoto() {
        PictureSelector.create(PersonInfoFragment.this)
                .openGallery(PictureMimeType.ofImage())
                .theme(R.style.picture_default_style)
                .maxSelectNum(1)
                .minSelectNum(1)
                .selectionMode(PictureConfig.MULTIPLE)
                .previewImage(true)
                .isCamera(true)
                .enableCrop(false)
                .compress(true)
                .glideOverride(160, 160)
                .previewEggs(true)
                .withAspectRatio(1, 1)
                .hideBottomControls(false)
                .isGif(true)
                .freeStyleCropEnabled(false)
                .circleDimmedLayer(false)
                .showCropFrame(false)
                .showCropGrid(false)
                .openClickSound(false)
                .selectionMedia(selectList)
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择
                    selectList = PictureSelector.obtainMultipleResult(data);
                    LocalMedia localMedia = selectList.get(0);
                    path = localMedia.getCompressPath();
                    img_photo.setImageURI(Uri.parse(path));
                    ((MineFragment)(PersonInfoFragment.this.getParentFragment())).imageView.setImageURI(Uri.parse(path));
                    AllFragment.img_head.setImageURI(Uri.parse(path));
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true  注意：音视频除外
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true  注意：音视频除外
                    // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                    //包括裁剪和压缩后的缓存，要在上传成功后调用，注意：需要系统sd卡权限
//                    PictureFileUtils.deleteCacheDirFile(MainActivity.this);
                    break;
            }
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if(!hidden){
            loadData();
        }
    }
}
